package com.gitlab.lucky.weixin.web.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.model.*;
import com.gitlab.lucky.common.exception.AesException;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.service.ConfigDataService;
import com.gitlab.lucky.common.service.PlatformDataService;
import com.gitlab.lucky.common.utils.PhoneUtil;
import com.gitlab.lucky.common.utils.TemplateMessageUtil;
import com.gitlab.lucky.common.utils.WXPublicUtils;
import com.gitlab.lucky.common.utils.XMLUtil;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import com.gitlab.lucky.eleme.service.IntegralConversionService;
import com.gitlab.lucky.eleme.service.LuckyRecordService;
import com.gitlab.lucky.eleme.service.SyncElemService;
import com.gitlab.lucky.weixin.service.WeixinGzhMsgService;
import com.gitlab.lucky.weixin.service.WeixinGzhAsyncService;
import com.gitlab.lucky.weixin.service.WeixinGzhIntegrationRecordService;
import com.gitlab.lucky.weixin.service.WeixinGzhUserService;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-04 16:50
 **/

@RestController
public class WeixinGzhController {
    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinGzhController.class);
    @Autowired
    private WeixinGzhMsgService weixinGzhMsgService;
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private WeixinGzhAsyncService weixinGzhAsyncService;
    @Autowired
    private ConfigDataService configDataService;
    @Autowired
    private PlatformDataService platformDataService;
    @Autowired
    private SyncElemService syncElemService;
    @Autowired
    private LuckyRecordService luckyRecordService;
    @Autowired
    private WeixinUtil weixinUtil;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;
    @Autowired
    private IntegralConversionService integralConversionService;


    /**
     * 微信服务器认证
     *
     * @param request
     * @return
     */
    @GetMapping("wx")
    public String verifyWXToken(HttpServletRequest request) throws AesException {
        String msgSignature = request.getParameter("signature");
        String msgTimestamp = request.getParameter("timestamp");
        String msgNonce = request.getParameter("nonce");
        String echoStr = request.getParameter("echostr");
        if (WXPublicUtils.verifyUrl(msgSignature, msgTimestamp, msgNonce)) {
            return echoStr;
        }
        return null;
    }

    /**
     * 为了支持多公众号接入,微信请求url中加platform参数做为区分
     *
     * @param req
     * @throws IOException
     */
    @PostMapping("wx")
    public String wx(HttpServletRequest req, HttpServletResponse response) throws Exception {
        Integer platform = Integer.parseInt(req.getParameter("platform"));
        if (platform == null) {
            return Constant.SUCCESS;
        }
        //接受微信服务器发送过来的XML形式的消息
        InputStream in = req.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String itemStr = "";//作为输出字符串的临时串，用于判断是否读取完毕
        while ((itemStr = reader.readLine()) != null) {
            sb.append(itemStr);
        }
        in.close();
        reader.close();
        //防止中文乱码
        response.setCharacterEncoding("UTF-8");
        return replyMessage(sb.toString(), platform);
    }

    /**
     * 解析收到的消息
     *
     * @param message
     * @return
     */
    public String replyMessage(String message, Integer platform) {
        //LOGGER.info("******消息："+message);
        //解析xml
        Document document = XMLUtil.readString2XML(message);
        Element root = document.getRootElement();
        return HandleMsg(root, platform,message);
    }

    /**
     * 消息处理
     *
     * @param root
     * @param platform
     * @return
     */
    private String HandleMsg(Element root, Integer platform,String message) {
        //取平台信息(appId,密钥等)
        PlatformData platformData = platformDataService.getPlatform(platform);
        //取公众号全局配置信息(文案)
        JSONObject configJSON = configDataService.getConfig(platformData.getPlatform());
        //收到的消息类型
        String msgType = XMLUtil.readNode(root, Constant.MSG_MSG_TYPE);
        //发送人openId
        String openId = XMLUtil.readNode(root, Constant.MSG_FROM_USER_NAME);
        //链接类型
        if (msgType.equals(Constant.LINK_TYPE)) {
            String url = XMLUtil.readNode(root, Constant.MSG_URL);
            //饿了么link
            if (url.contains(Constant.ELEM_URL)) {
                LOGGER.info("请求功能:抢饿了么红包,请求者openId:{},请求平台:{}", openId, platformData.getPlatform());
                return elemLucky(openId, configJSON, url, platformData, CodeEnum.ELEM.getCode(), null);
            }
            //美团link
            if (url.contains(Constant.MEITUAN_URL)) {
                LOGGER.info("请求功能:抢美团红包,请求者openId:{},请求平台:{}", openId, platformData.getPlatform());
                return weixinGzhMsgService.resultText(openId, Constant.NOT_MEITUAN_MSG, platformData.getFromUserName());
            }
        }
        //文本类型
        if (msgType.equals(Constant.TEXT_TYPE)) {
            String content = XMLUtil.readNode(root, Constant.MSG_CONTENT);
            //绑定手机号
            if (PhoneUtil.isNum(content)) {
                return phone(openId, platformData, content, configJSON);
            }
            //饿了么链接抢红包
            if (content.contains(Constant.ELEM_URL)) {
                //return elemLucky(openId, configJSON, content, platformData, CodeEnum.ELEM.getCode(), null);
                return weixinGzhMsgService.resultText(openId, configJSON.getString(Constant.MSG_MQ), platformData.getFromUserName());
            }
            //饿了么订单号抢红包
            if (content.length() == Constant.ELEM_ORDER_NUM_LENGTH && !content.contains(" ")) {
                //elemLucky(openId, configJSON, null, platformData, CodeEnum.ELEM.getCode(), content);
                return weixinGzhMsgService.resultText(openId, configJSON.getString(Constant.MSG_MQ), platformData.getFromUserName());
            }
            //签到
            if (content.equals(Constant.SIGN_STR)) {
                signIn(openId, platformData, configJSON);
            }
            //邀请海报
            if (content.equals(Constant.INVITE)) {
                return inviteQr(platformData, openId, configJSON);
            }
            //福利
            if (content.equals(Constant.MEITUAN) || content.equals(Constant.FULI)) {
                return fuli(openId, platformData, configJSON);
            }
            //转积分
            if (content.equals(Constant.TURN)) {
                return turn(openId, platformData, configJSON);
            }
            //客服
            if (content.equals(Constant.SERVICE)) {
                return service(openId, platformData, configJSON);
            }
            //暗号(供自己或朋友使用)
            if (content.equals(Constant.PWD)) {
                pwd(platformData, openId);
            }
            //积分兑换
            if (content.length() == Constant.INTEGRAL_CONVERSION_LENGTH && !content.contains(" ")) {
                return conversion(openId, platformData, configJSON,content);
            }
        }
        //事件类型
        if (msgType.equals(Constant.EVENT_TYPE)) {
            //模版消息和一个经纬度xml事件不处理
            if(XMLUtil.readNode(root, Constant.MSG_EVENT).equals(Constant.EVENT_KEY_TEMPLATESENDJOBFINISH) || XMLUtil.readNode(root, Constant.MSG_EVENT).equals(Constant.EVENT_KEY_LOCATION)){
                return Constant.SUCCESS;
            }
            String eventKey = XMLUtil.readNode(root, Constant.MSG_EVENT_KEY);
            String event = XMLUtil.readNode(root, Constant.MSG_EVENT);
            //订阅事件
            if (event.equals(Constant.EVENT_KEY_SUBSCRIBE)) {
                //新人存库，重新关注更新信息
                return subscribe(openId, platformData, configJSON);
            }
            //签到事件
            if (eventKey.equals(Constant.EVENT_KEY_QIANDAO)) {
                return signIn(openId, platformData, configJSON);
            }
            //邀请海报事件
            if (eventKey.equals(Constant.EVENT_KEY_YAOQING)) {
                return inviteQr(platformData, openId, configJSON);
            }
            //免费饿了么、美团红包事件
            if (eventKey.equals(Constant.EVENT_KEY_FULI)) {
                return fuli(openId, platformData, configJSON);
            }
            //自定义事件 - 读取数据库配置
            if (eventKey.equals(Constant.EVENT_KEY_ZIDINGYI)) {
                return zidingyi(openId, platformData, configJSON);
            }
        }
        return Constant.SUCCESS;
    }

    /**
     * 暗号(供自己或朋友使用)
     */
    private void pwd(PlatformData platformData, String openId) {
        LuckyRecord luckyRecord = luckyRecordService.selectPwd();
        if (luckyRecord != null) {
            weixinGzhMsgService.resultServerNews(
                    openId,
                    Constant.REPLY,
                    Constant.REPLY2,
                    String.format(Constant.URL, luckyRecord.getSn()),
                    platformData.getAvatar(),
                    platformData.getPlatform());
        }
    }

    /**
     * 绑定手机号
     */
    private String phone(String openId, PlatformData platformData, String phone, JSONObject json) {
        LOGGER.info("\n请求功能:绑定手机号,请求者openId:{},请求平台:{}", openId, platformData.getPlatform()+"\n");
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        //用户信息存库
        WeixinGzhUser wxUserInfo = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        if (wxUserInfo == null) {
            weixinGzhUserService.insertUserInfo(openId, platformData.getPlatform(), json);
        } else {
            weixinGzhUserService.updateUserInfo(openId, phone, platformData.getPlatform());
        }
        //绑定成功 发送消息
        if(json.getInteger(Constant.IS_TEMPLATE) == 1){
            List<TemplateMessageUtil> templateParams = new ArrayList<>();
            TemplateMessageUtil first = new TemplateMessageUtil("first", "您已完成账号绑定", "#9ACD32");
            TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", "绑定成功", "");
            TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", phone, "");
            TemplateMessageUtil remark = new TemplateMessageUtil("remark", "", "");
            templateParams.add(first);
            templateParams.add(keyword1);
            templateParams.add(keyword2);
            templateParams.add(remark);
            weixinGzhMsgService.sendWarningByWechat(openId,platformData.getPlatform(),json.getString(Constant.PHONE_TEMPLATE_ID),templateParams,"false");
            return Constant.SUCCESS;
        }
        return weixinGzhMsgService.resultText(openId, json.getString(Constant.PHONE_SUCCESS), platformData.getFromUserName());
    }

    /**
     * 返回邀请二维码
     *
     * @param platformData
     * @param openId
     * @param json
     * @return
     */
    private String inviteQr(PlatformData platformData, String openId, JSONObject json) {
        //通过openId查询用户信息
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        //用户不存在
        if (weixinGzhUser == null) {
            weixinGzhUserService.insertUserInfo(openId, platformData.getPlatform(), json);
        }
        //异步发送二维码
        LOGGER.info("\n请求功能:生成邀请二维码,请求者openId:{},请求平台:{}", openId, platformData.getPlatform()+"\n");
        weixinGzhAsyncService.getQRCode(openId, platformData.getPlatform(), json.getString(Constant.IMAGE_BJ));
        return weixinGzhMsgService.resultText(openId, String.format(json.getString(Constant.INIT_IMAGE),json.getString(Constant.INVITATION_COUNT)), platformData.getFromUserName());
    }

    /**
     * 订阅存库
     *
     * @param invite       受邀者
     * @param platformData
     * @param json
     */
    @Transactional
    public String subscribe(String invite, PlatformData platformData, JSONObject json) {
        //通过openId查询用户信息
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(invite, platformData.getPlatform());
        //用户不存在
        if (weixinGzhUser == null) {
            //初始化用户信息入库
            weixinGzhUser = weixinGzhUserService.insertUserInfo(invite, platformData.getPlatform(), json);
            LOGGER.info(",openId:{}", invite);
            //邀请人openId
            String openId = weixinGzhUser.getQrSceneStr();
            if (StringUtils.isNotBlank(openId) && !openId.equals(invite)) {
                //查询邀请人
                WeixinGzhUser weixinGzhUsers = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
                if (weixinGzhUsers != null) {
                    weixinGzhUsers.setIntegration(weixinGzhUsers.getIntegration() + json.getInteger(Constant.INVITATION_COUNT));
                    //邀请人+积分
                    LOGGER.info("\n邀请人+积分,邀请人:{}",openId);
                    weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUsers);
                    WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
                    weixinGzhIntegrationRecord.setCreateTime(new Date());
                    weixinGzhIntegrationRecord.setPlatform(platformData.getPlatform());
                    weixinGzhIntegrationRecord.setType(CodeEnum.INVITE.getCode());
                    weixinGzhIntegrationRecord.setOpenId(openId);
                    weixinGzhIntegrationRecord.setIntegration("+"+json.get(Constant.INVITATION_COUNT));
                    weixinGzhIntegrationRecord.setIntegrationBalance(weixinGzhUsers.getIntegration());
                    weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);
                    //邀请成功发送通知 邀请通知模版微信失效部分平台没有
                    if(json.getInteger(Constant.IS_TEMPLATE) == 1 && !StringUtils.isBlank(json.getString(Constant.INVITATION_TEMPLATE_ID))) {
                        List<TemplateMessageUtil> templateParams = new ArrayList<>();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        TemplateMessageUtil first = new TemplateMessageUtil("first", "您邀请的用户接受了您的邀请", "#9ACD32");
                        TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", weixinGzhUser.getNickname(), "");
                        TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", df.format(new Date()), "");
                        TemplateMessageUtil remark = new TemplateMessageUtil("remark", "增加积分："+json.getInteger(Constant.INVITATION_COUNT)+"\\r\\n"+"当前积分："+weixinGzhUsers.getIntegration(), "");
                        templateParams.add(first);
                        templateParams.add(keyword1);
                        templateParams.add(keyword2);
                        templateParams.add(remark);
                        String url = Constant.DOMAIN_URL+"/inviteListView?openId="+openId+"&platform="+platformData.getPlatform();
                        weixinGzhMsgService.sendWarningByWechat(openId, platformData.getPlatform(), json.getString(Constant.INVITATION_TEMPLATE_ID), templateParams,url);
                    }else{
                        weixinGzhMsgService.resultServerText(
                                openId,
                                String.format(json.getString(Constant.INVITE_SUCCESS)
                                        , weixinGzhUser.getNickname()
                                        , json.getInteger(Constant.INVITATION_COUNT)
                                        , weixinGzhUsers.getIntegration())
                                , platformData.getPlatform());
                    }

                    LOGGER.info("\n邀请成功openId:{},parentOpenId",invite,openId);
                }
            }
        } else {
            LOGGER.info("更新用户信息,openId:{}", invite);
            //更新用户信息
            weixinGzhUserService.updateUserInfo(invite, null, platformData.getPlatform());
            String againWelcome = String.format(json.getString(Constant.AGAIN_WELCOME));
            return weixinGzhMsgService.resultText(invite, againWelcome, platformData.getFromUserName());
        }
        String welcome = String.format(json.getString(Constant.WELCOME), json.getString(Constant.INIT_USER_COUNT));
        return weixinGzhMsgService.resultText(invite, welcome, platformData.getFromUserName());
    }

    /**
     * 签到
     *
     * @return
     */
    public String signIn(String openId, PlatformData platformData, JSONObject json) {
        if (json.getInteger(Constant.IS_SIGN) == Constant.SIGN_IN_FALSE) {
            //签到功能暂时关闭
            return weixinGzhMsgService.resultText(openId, Constant.SIGN_MSG, platformData.getFromUserName());
        }

        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        if (weixinGzhUser == null) {
            weixinGzhUser = weixinGzhUserService.insertUserInfo(openId, platformData.getPlatform(), json);
        }
        LOGGER.info("\n请求功能:签到,请求者openId:{},请求平台:{},请求者:{}", openId, platformData.getPlatform(), weixinGzhUser.getPhone());
        //签到失败，已经签到过了
        if (weixinGzhUser.getIsSignIn() == Constant.SIGN_IN_TRUE) {

            if(json.getInteger(Constant.IS_TEMPLATE) == 1 && (platformData.getPlatform()==3 || platformData.getPlatform()==8)){
                List<TemplateMessageUtil> templateParams = new ArrayList<>();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                TemplateMessageUtil first = new TemplateMessageUtil("first", "", "#9ACD32");
                TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", df.format(new Date()), "");
                TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", "今日已经签到过", "");
                TemplateMessageUtil remark = new TemplateMessageUtil("remark", "如有疑问，请联系客服", "");
                templateParams.add(first);
                templateParams.add(keyword1);
                templateParams.add(keyword2);
                templateParams.add(remark);
                weixinGzhMsgService.sendWarningByWechat(openId,platformData.getPlatform(),json.getString(Constant.SIGN_TEMPLATE_FAILURE_ID),templateParams,"false");
                return Constant.SUCCESS;
            }

            return weixinGzhMsgService.resultText(openId, json.getString(Constant.SIGN_IN_FAIL), platformData.getFromUserName());
        }
        weixinGzhUser.setIsSignIn(Constant.SIGN_IN_TRUE);
        Integer count = weixinGzhUser.getIntegration() + json.getInteger(Constant.SIGN_IN_COUNT);
        weixinGzhUser.setIntegration(count);
        weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);
        WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
        weixinGzhIntegrationRecord.setCreateTime(new Date());
        weixinGzhIntegrationRecord.setPlatform(platformData.getPlatform());
        weixinGzhIntegrationRecord.setType(CodeEnum.SIGN.getCode());
        weixinGzhIntegrationRecord.setOpenId(openId);
        weixinGzhIntegrationRecord.setIntegration("+"+json.getInteger(Constant.SIGN_IN_COUNT));
        weixinGzhIntegrationRecord.setIntegrationBalance(count);
        weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);
        String msg = String.format(json.getString(Constant.SIGN_IN_SUCCESS), json.getInteger(Constant.SIGN_IN_COUNT),count);
        //签到成功
        if(json.getInteger(Constant.IS_TEMPLATE) == 1 && !StringUtils.isBlank(Constant.SIGN_TEMPLATE_ID)){
            List<TemplateMessageUtil> templateParams = new ArrayList<>();
            TemplateMessageUtil first = new TemplateMessageUtil("first", "恭喜您签到积分增加成功，明日再来哦", "#9ACD32");
            TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", json.getString(Constant.SIGN_IN_COUNT), "");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", count.toString(), "");
            TemplateMessageUtil keyword3 = new TemplateMessageUtil("keyword3", df.format(new Date()), "");
            TemplateMessageUtil remark = new TemplateMessageUtil("remark", "", "");
            templateParams.add(first);
            templateParams.add(keyword1);
            templateParams.add(keyword2);
            templateParams.add(keyword3);
            templateParams.add(remark);
            String url = Constant.DOMAIN_URL+"/integrationRecordView?openId="+openId+"&platform="+platformData.getPlatform();
            weixinGzhMsgService.sendWarningByWechat(openId,platformData.getPlatform(),json.getString(Constant.SIGN_TEMPLATE_ID),templateParams,url);
            return Constant.SUCCESS;
        }
        return weixinGzhMsgService.resultText(openId, msg, platformData.getFromUserName());
    }

    public String service(String openId, PlatformData platformData, JSONObject json) {
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        if (weixinGzhUser == null) {
            weixinGzhUser = weixinGzhUserService.insertUserInfo(openId, platformData.getPlatform(), json);
        }
        String msg = "";
        if(weixinGzhUser.getPlatform() == 3 || weixinGzhUser.getPlatform() == 8){
            msg = "很高兴为您服务\n客服微信:suhaiyuan_";
        }else{
            msg = "请点击《个人中心》-《联系客服》";
        }
        return weixinGzhMsgService.resultText(openId, msg, platformData.getFromUserName());
    }

    /**
     * 自定义事件内容1
     * @param openId
     * @param platformData
     * @param json
     * @return
     */
    public String fuli(String openId, PlatformData platformData, JSONObject json) {
        String msg = json.getString(Constant.ZIDINGYI_CONTENT1);
         return weixinGzhMsgService.resultText(openId, msg, platformData.getFromUserName());
    }

    /**
     * 自定义事件内容
     * @param openId
     * @param platformData
     * @param json
     * @return
     */
    public String zidingyi(String openId, PlatformData platformData, JSONObject json) {
        String msg = json.getString(Constant.ZIDINGYI_CONTENT);
        return weixinGzhMsgService.resultText(openId, msg, platformData.getFromUserName());
    }

    /**
     * 积分兑换
     * @param openId
     * @param platformData
     * @param json
     * @return
     */
    public String conversion(String openId, PlatformData platformData, JSONObject json,String content) {

        if(json.getInteger(Constant.IS_CONVERSION) == Constant.FALSE){
            return weixinGzhMsgService.resultText(openId, "未开放此功能，请联系客服", platformData.getFromUserName());
        }

        IntegralConversion integralConversion = integralConversionService.selectByRandomCode(content);
        if(integralConversion==null){
            return weixinGzhMsgService.resultText(openId, "兑换码错误或已兑换过！\n如有问题，请联系客服", platformData.getFromUserName());
        }

        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());

        //积分流水
        WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
        weixinGzhIntegrationRecord.setCreateTime(new Date());
        weixinGzhIntegrationRecord.setPlatform(platformData.getPlatform());
        weixinGzhIntegrationRecord.setType(CodeEnum.ACTIVITY.getCode());
        weixinGzhIntegrationRecord.setOpenId(openId);
        weixinGzhIntegrationRecord.setIntegration("+"+integralConversion.getIntegration());
        weixinGzhIntegrationRecord.setIntegrationBalance(weixinGzhUser.getIntegration()+integralConversion.getIntegration());
        weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);

        //增加兑换积分
        weixinGzhUser.setIntegration(weixinGzhUser.getIntegration()+integralConversion.getIntegration());
        weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);

        //更新兑换信息
        integralConversion.setIsReset(Constant.TRUE);
        integralConversion.setUpdateTime(new Date());
        integralConversion.setOpenId(openId);
        integralConversion.setPlatform(platformData.getPlatform());
        integralConversionService.updateByPrimaryKeySelective(integralConversion);

        if(json.getInteger(Constant.IS_TEMPLATE) == 1 && !StringUtils.isBlank(json.getString(Constant.INVITATION_CONVERSION_TEMPLATE_ID))){
            List<TemplateMessageUtil> templateParams = new ArrayList<>();
            TemplateMessageUtil first = new TemplateMessageUtil("first", "恭喜您，积分兑换成功。", "#9ACD32");
            TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", content, "");
            TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", platformData.getRemark(), "");
            TemplateMessageUtil keyword3 = new TemplateMessageUtil("keyword3", integralConversion.getIntegration()+"积分", "");
            TemplateMessageUtil keyword4 = new TemplateMessageUtil("keyword4", "永久", "");
            TemplateMessageUtil keyword5 = new TemplateMessageUtil("keyword5", weixinGzhUser.getIntegration()+"积分", "");
            TemplateMessageUtil remark = new TemplateMessageUtil("remark", "", "");
            templateParams.add(first);
            templateParams.add(keyword1);
            templateParams.add(keyword2);
            templateParams.add(keyword3);
            templateParams.add(keyword4);
            templateParams.add(keyword5);
            templateParams.add(remark);
            String url = Constant.DOMAIN_URL+"/integrationRecordView?openId="+openId+"&platform="+platformData.getPlatform();
            weixinGzhMsgService.sendWarningByWechat(openId,platformData.getPlatform(),json.getString(Constant.INVITATION_CONVERSION_TEMPLATE_ID),templateParams,url);
            return Constant.SUCCESS;
        }

        return weixinGzhMsgService.resultText(openId, "恭喜您，兑换成功"+integralConversion.getIntegration()+"积分！", platformData.getFromUserName());
    }

    /**
     * 同平台公众号转积分
     * @param openId
     * @param platformData
     * @param json
     * @return
     */
    public String turn(String openId, PlatformData platformData, JSONObject json) {

        if(platformData.getPlatform()!=8){
            return weixinGzhMsgService.resultText(openId, "未开放此功能，请联系客服", platformData.getFromUserName());
        }
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        LOGGER.info("\n转积分 ---------------------------------------"+openId+"---"+weixinGzhUser.getPhone()+"\n");
        if (weixinGzhUser == null) {
            weixinGzhUser = weixinGzhUserService.insertUserInfo(openId, platformData.getPlatform(), json);
        }
        if(StringUtils.isBlank(weixinGzhUser.getPhone())){
            return weixinGzhMsgService.resultText(openId, "请先绑定饿了么手机号\n将手机号发送给此公众号即可绑定", platformData.getFromUserName());
        }

        WeixinGzhUser weixinGzhUser6 = weixinGzhUserService.selectByPhone(weixinGzhUser.getPhone(), 6);
        if(weixinGzhUser6 == null){
            return weixinGzhMsgService.resultText(openId, "转积分失败\n因您在之前公众号未绑定过手机号\n如有问题请联系客服\n您当前积分余额为："+weixinGzhUser.getIntegration(), platformData.getFromUserName());
        }
        //2个平台都验证 以防作弊
        if(weixinGzhUser.getIsReset()==1 || weixinGzhUser6.getIsReset()==1){
            return weixinGzhMsgService.resultText(openId, "您已转过积分\n如有问题请联系客服处理\n您当前积分余额为："+weixinGzhUser.getIntegration(), platformData.getFromUserName());
        }
        if(StringUtils.isBlank(weixinGzhUser6.getPhone())){
            return weixinGzhMsgService.resultText(openId, "转积分失败\n因您在之前公众号未绑定过手机号\n如有问题请联系客服\n您当前积分余额为："+weixinGzhUser.getIntegration(), platformData.getFromUserName());
        }

        Integer igt = weixinGzhUser.getIntegration()+weixinGzhUser6.getIntegration();
        weixinGzhUser.setIntegration(igt);
        weixinGzhUser.setIsReset(1);
        weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);
        weixinGzhUser6.setIsReset(1);
        weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser6);
        LOGGER.info("\n转积分成功 ---------------------------------------"+openId+"---"+weixinGzhUser.getPhone()+"\n");
        return weixinGzhMsgService.resultText(openId, "转积分成功\n您之前剩余"+weixinGzhUser6.getIntegration()+"积分\n转后积分余额为："+igt+"积分", platformData.getFromUserName());
    }

    /**
     * 抢包前的验证,验证通过开始抢包
     *
     * @param openId
     * @return
     */
    public String elemLucky(String openId, JSONObject json, String url, PlatformData platformData, int type, String orderNum) {
        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
        //用户不存在
        if (weixinGzhUser == null) {
            weixinGzhUser = weixinGzhUserService.insertUserInfo(openId, platformData.getPlatform(), json);
        }
        //如果不存在，需要绑定手机号
        if (StringUtils.isBlank(weixinGzhUser.getPhone())) {
            return weixinGzhMsgService.resultText(openId, json.getString(Constant.PHONE_FAIL), platformData.getFromUserName());
        }
        //如果积分不足，提示去充值
        if (weixinGzhUser.getIntegration() < json.getInteger(Constant.MIN_COUNT)) {
            return weixinGzhMsgService.resultText(openId, String.format(json.getString(Constant.NOT_COUNT), json.getInteger(Constant.MIN_COUNT),weixinGzhUser.getIntegration()), platformData.getFromUserName());
        }
        //防止重复请求
        if (weixinUtil.isSubmit(platformData.getPlatform(), openId)) {
            return weixinGzhMsgService.resultText(openId, json.getString(Constant.REPEAT_REQUEST), platformData.getFromUserName());
        }
        //饿了么
        if (type == CodeEnum.ELEM.getCode()) {
            syncElemService.syncElemQhb(weixinGzhUser, openId, json, platformData, orderNum, url);
        }
        return weixinGzhMsgService.resultText(openId, json.getString(Constant.MSG_MQ), platformData.getFromUserName());
    }

    /**
     * 助手查询余额接口
     * @return
     */
    @GetMapping("money")
    public String money(String token){
        if(!"Ma0WbSaTGSc82I94A3Oc0D1oV7Za00".equals(token) || token == null){
            return "token未授权";
        }
        String url = "https://xjj.open.xjj186.cn/user/money";
        HttpRequest request = HttpUtil.createGet(url)
                .header("Content-type", "application/json;charset=utf-8")
                .header("Token", token);
        String body = request.execute().body();
        cn.hutool.json.JSONObject bodyJson = XML.toJSONObject(body);
        JSONObject responseWrapper = JSON.parseObject(bodyJson.get("ResponseWrapper").toString());
        String data = responseWrapper.getString("data");
        double v = Double.parseDouble(data);
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(v*2);//*2
    }

}

